package com.halflife.comeElectricity.orderMng.order;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.halflife.comeElectricity.admin.DateUtil;
import com.halflife.comeElectricity.admin.NavStatic;
import com.halflife.comeElectricity.basic.address.Address;
import com.halflife.comeElectricity.member.rider.PayLog;
import com.halflife.comeElectricity.member.rider.PayLogRepository;
import com.halflife.comeElectricity.orderMng.cancel.*;
import com.halflife.comeElectricity.orderMng.history.HistoryOrder;
import com.halflife.comeElectricity.orderMng.history.HistoryOrderExtRepository;
import com.halflife.comeElectricity.orderMng.history.HistoryOrderRepository;
import com.halflife.comeElectricity.orderMng.order.vo.OrderVO;
import com.halflife.comeElectricity.orderMng.reFund.ReFundEnum;
import com.halflife.comeElectricity.orderMng.reFund.ReFundOrder;
import com.halflife.comeElectricity.orderMng.reFund.ReFundOrderRepository;
import com.halflife.framework.converter.MapHandler;
import com.halflife.framework.domain.Page;
import com.halflife.pay.wxpay.WXPayAgent;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhaoyf on 2018/2/23.
 */
@Controller
@RequestMapping("/admin")
public class OrderAdminController {

    private Logger log = LoggerFactory.getLogger(OrderRiderController.class);

    @Resource
    private OrderRepository orderRepository;
    @Resource
    private HistoryOrderRepository historyOrderRepository;
    @Resource
    private HistoryOrderExtRepository historyOrderExtRepository;
    @Resource
    private CancelOrderRepository cancelOrderRepository;
    @Resource
    private OrderExtRepository orderExtRepository;
    @Resource
    private CancelOrderExtRepository cancelOrderExtRepository;
    @Resource
    private PayLogRepository payLogRepository;
    @Resource
    private ReFundOrderRepository reFundOrderRepository;
    @Resource
    private CancelOrderController cancelOrderController;

    @RequestMapping("/admin_order/list")
    public String gotoOrderList(String merchartName, String riderName, String dateRangeBe, String dateRangeEn, Integer pageNo, Integer pageSize, HttpServletRequest request,
                                HttpServletResponse response, Model model) {
       // Merchant merchant  =  ShiroUtil.getMerchant();
        //推送分页Map参数
        if(pageNo==null)
            pageNo= 1;
        if(pageSize==null)
            pageSize= 20;
        //推送查询参数
        HashMap<String, Object> param = new HashMap();
        if(dateRangeBe!=null && dateRangeBe!="")
            param.put("dateRangeBe", DateUtil.transForMilliSecondByTim(dateRangeBe));
        if(dateRangeEn!=null && dateRangeEn!="")
            param.put("dateRangeEn",DateUtil.transForMilliSecondByTim(dateRangeEn));
        if(merchartName!=null && merchartName!="")
            param.put("merchartName", merchartName);
        if(riderName!=null && riderName!="")
            param.put("riderName", riderName);
        param.put("currentPage", (pageNo-1)*pageSize);
        param.put("pageSize", pageSize);
       // param.put("merchantId", merchant.getId());
        int totalCount = orderRepository.selectCountOrderByPage(param);
        //查询列表
        List<Order> list = orderRepository.selectOrderByPage(param);
        //计算总页数
        int totalPage = totalCount/pageSize;
        if(totalCount%pageSize!= 0)
            totalPage++;

        model.addAttribute("dateRangeBe",dateRangeBe);
        model.addAttribute("dateRangeEn",dateRangeEn);
        model.addAttribute("merchartName",merchartName);
        model.addAttribute("riderName",riderName);
        model.addAttribute("list",list);
        model.addAttribute("totalPage",totalPage);
        model.addAttribute("pageNo",pageNo);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("totalCount",totalCount);
        return "order/list";
    }

    @RequestMapping("/admin_order/history/list")
    public String gotoOrderHistoryList(String merchartName, String riderName, String dateRangeBe, String dateRangeEn, Integer pageNo, Integer pageSize, HttpServletRequest request,
                                       HttpServletResponse response, Model model) {
        // Merchant merchant  =  ShiroUtil.getMerchant();
        //推送分页Map参数
        if(pageNo==null)
            pageNo= 1;
        if(pageSize==null)
            pageSize= 20;
        HashMap<String, Object> param = new HashMap();
        if(dateRangeBe!=null && dateRangeBe!="")
            param.put("dateRangeBe", DateUtil.transForMilliSecondByTim(dateRangeBe));
        if(dateRangeEn!=null && dateRangeEn!="")
            param.put("dateRangeEn",DateUtil.transForMilliSecondByTim(dateRangeEn));
        if(merchartName!=null && merchartName!="")
            param.put("merchartName", merchartName);
        if(riderName!=null && riderName!="")
            param.put("riderName", riderName);
        param.put("currentPage", (pageNo-1)*pageSize);
        param.put("pageSize", pageSize);
        // param.put("merchantId", merchant.getId());
        int totalCount = historyOrderRepository.selectHistoryCountOrderByPage(param);
        //查询列表
        List<HistoryOrder> list = historyOrderRepository.selectHistoryOrderByPage(param);
        //计算总页数
        int totalPage = totalCount/pageSize;
        if(totalCount%pageSize!= 0)
            totalPage++;
        model.addAttribute("dateRangeBe",dateRangeBe);
        model.addAttribute("dateRangeEn",dateRangeEn);
        model.addAttribute("merchartName",merchartName);
        model.addAttribute("riderName",riderName);
        model.addAttribute("list",list);
        model.addAttribute("totalPage",totalPage);
        model.addAttribute("pageNo",pageNo);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("totalCount",totalCount);
        return "order/history/list";
    }

    @RequestMapping("/admin_order/cancel/list")
    public String gotoOrderCancelList(String merchartName, String riderName, String dateRangeBe, String dateRangeEn, Integer pageNo, Integer pageSize, HttpServletRequest request,
                                      HttpServletResponse response, Model model) {
        // Merchant merchant  =  ShiroUtil.getMerchant();
        //推送分页Map参数
        if(pageNo==null)
            pageNo= 1;
        if(pageSize==null)
            pageSize= 20;
        HashMap<String, Object> param = new HashMap();
        if(dateRangeBe!=null && dateRangeBe!="")
            param.put("dateRangeBe", DateUtil.transForMilliSecondByTim(dateRangeBe));
        if(dateRangeEn!=null && dateRangeEn!="")
            param.put("dateRangeEn",DateUtil.transForMilliSecondByTim(dateRangeEn));
        if(merchartName!=null && merchartName!="")
            param.put("merchartName", merchartName);
        if(riderName!=null && riderName!="")
            param.put("riderName", riderName);
        param.put("currentPage", (pageNo-1)*pageSize);
        param.put("pageSize", pageSize);
        // param.put("merchantId", merchant.getId());
        int totalCount = cancelOrderRepository.selectCancelCountOrderByPage(param);
        //查询列表
        List<CancelOrder> list = cancelOrderRepository.selectCancelOrderByPage(param);
        //计算总页数
        int totalPage = totalCount/pageSize;
        if(totalCount%pageSize!= 0)
            totalPage++;
        model.addAttribute("dateRangeBe",dateRangeBe);
        model.addAttribute("dateRangeEn",dateRangeEn);
        model.addAttribute("merchartName",merchartName);
        model.addAttribute("riderName",riderName);
        model.addAttribute("list",list);
        model.addAttribute("totalPage",totalPage);
        model.addAttribute("pageNo",pageNo);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("totalCount",totalCount);
        return "order/cancel/list";
    }

    /**
     * 生成取消訂單 並刪除訂單 add by liuj
     * @param orderId
     * @param request
     */
    @PostMapping("/generatorCancel/{orderId}")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity<Map> add(@PathVariable Integer orderId, HttpServletRequest request){
        Map map = new HashMap();
        try {
            BeanUtilsBean beanUtilsBean = new BeanUtilsBean();
            beanUtilsBean.getConvertUtils().register(new org.apache.commons.beanutils.converters.BigDecimalConverter(null), BigDecimal.class);
            //查詢訂單以及訂單詳情
            if(orderId!=null) {
                //获取订单
                Order order = orderRepository.selectByPrimaryKey(orderId);
                OrderExt orderExt = orderExtRepository.selectByPrimaryKey(order.getId());
                //创建退款订单对象 add by liuj3
                ReFundOrder reFundOrder = new ReFundOrder();
                reFundOrder.setCreateTime(Calendar.getInstance().getTimeInMillis());
                //微信订单号
                reFundOrder.setTransaction_id(order.getTransaction_id());
                //商户订单号 out_trade_no 为orderId
                reFundOrder.setOut_trade_no(new String().valueOf(order.getId()));
                reFundOrder.setRefund_status(new String().valueOf(ReFundEnum.PROCESS.m_orderStatus));
                if(orderExt.getFee()==null)
                    orderExt.setFee(new BigDecimal(0));
                if(orderExt.getAmount()==null)
                    orderExt.setAmount(new BigDecimal(0));
                reFundOrder.setTotal_fee(orderExt.getAmount().add(orderExt.getFee()).multiply(new BigDecimal("100")).intValue());
                reFundOrder.setRefund_fee(orderExt.getAmount().add(orderExt.getFee()).multiply(new BigDecimal("100")).intValue());
                reFundOrderRepository.insert(reFundOrder);
                log.debug("====退款订单id:"+reFundOrder.getId());
                //发起退款申请
                //调用初始化退款服务代理
                WXPayAgent agent = new WXPayAgent(order.getId().toString(), order.getTransaction_id(),
                        orderExt.getAmount().add(orderExt.getFee()).multiply(new BigDecimal("100")).intValue(),orderExt.getAmount().add(orderExt.getFee()).multiply(new BigDecimal("100")).intValue(),
                        reFundOrder.getId().toString(),"商户取消订单");
                String result = agent.doRefund(orderExt.getPayType());
                if (result != null) {
                    reFundOrder.setRefund_id(result);
                    reFundOrderRepository.updateByPrimaryKeySelective(reFundOrder);
                    Integer merchantId = order.getMerchantId();
                    Long createTime = order.getCreateTime();
                    cancelOrderController.add(order.getId());
                    //插入通知

                }
            }
            //return Result.Ok();
            return new ResponseEntity<Map>(map, HttpStatus.OK);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
           // return Result.No("系统异常");
            return new ResponseEntity<Map>(map, HttpStatus.EXPECTATION_FAILED);
        }
    }

    @RequestMapping("/admin_order/reFundOrder/list")
    public String gotoReFundOrderList(String out_trade_no, String dateRangeBe, String dateRangeEn, Integer pageNo, Integer pageSize, HttpServletRequest request,
                                      HttpServletResponse response, Model model) {
        // Merchant merchant  =  ShiroUtil.getMerchant();
        //推送分页Map参数
        if(pageNo==null)
            pageNo= 1;
        if(pageSize==null)
            pageSize= 20;
        HashMap<String, Object> param = new HashMap();
        if(dateRangeBe!=null && dateRangeBe!="")
            param.put("dateRangeBe", DateUtil.transForMilliSecondByTim(dateRangeBe));
        if(dateRangeEn!=null && dateRangeEn!="")
            param.put("dateRangeEn",DateUtil.transForMilliSecondByTim(dateRangeEn));
        if(out_trade_no!=null && out_trade_no!="")
            param.put("out_trade_no", out_trade_no);
        param.put("currentPage", (pageNo-1)*pageSize);
        param.put("pageSize", pageSize);
        // param.put("merchantId", merchant.getId());
        int totalCount = reFundOrderRepository.selectReFundOrderCountByPage(param);
        //查询列表
        List<ReFundOrder> list = reFundOrderRepository.selectReFundOrderByPage(param);
        //计算总页数
        int totalPage = totalCount/pageSize;
        if(totalCount%pageSize!= 0)
            totalPage++;
        model.addAttribute("dateRangeBe",dateRangeBe);
        model.addAttribute("dateRangeEn",dateRangeEn);
        model.addAttribute("out_trade_no",out_trade_no);
        model.addAttribute("list",list);
        model.addAttribute("totalPage",totalPage);
        model.addAttribute("pageNo",pageNo);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("totalCount",totalCount);
        return "order/reFund/list";
    }

    @GetMapping("/admin_order/order_vo/{id}")
    public String getOrderVObyId(@PathVariable Integer id, HttpServletRequest request,
                                 HttpServletResponse response, Model model) {
        OrderVO orderExt = orderExtRepository.selectVOById(id);
        Gson gson = new Gson();
        Address s =  gson.fromJson(orderExt.getStartPlace(), Address.class);
        List<Address> d =  gson.fromJson(orderExt.getDestination(), new TypeToken<List<Address>>(){}.getType());
        model.addAttribute("startPlace",s);
        model.addAttribute("destination",d);
        model.addAttribute("orderExt",orderExt);
        return "order/info";
    }
    @GetMapping("/admin_order/cancel_vo/{id}")
    public String getCancelVObyId(@PathVariable Integer id, HttpServletRequest request,
                                  HttpServletResponse response, Model model) {
        OrderVO orderExt = cancelOrderExtRepository.selectVOById(id);
        Gson gson = new Gson();
        model.addAttribute("orderExt",orderExt);
        model.addAttribute("orderExt",orderExt);
        return "order/cancel/info";
    }
    @GetMapping("/admin_order/history_vo/{id}")
    public String getHistoryVObyId(@PathVariable Integer id, HttpServletRequest request,
                                   HttpServletResponse response, Model model) {
        OrderVO orderExt = historyOrderExtRepository.selectVOById(id);
        Gson gson = new Gson();
        model.addAttribute("orderExt",orderExt);
        model.addAttribute("orderExt",orderExt);
        return "order/history/info";
    }

    @RequestMapping("/admin_order/payLog/list")
    public String gotoPayLogList(Integer riderId,String riderName, String dateRangeBe, String dateRangeEn, Integer pageNo, Integer pageSize, HttpServletRequest request,
                                 HttpServletResponse response, Model model) {
        // Merchant merchant  =  ShiroUtil.getMerchant();
        //推送分页Map参数
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("riderId", riderId);
        queryParam.put("status", 1);
        List<PayLog> list = payLogRepository.selectAll(queryParam);
        model.addAttribute("list", list);
        model.addAttribute("riderId", riderId);
        return "order/payLog/list";
    }

}
